package com.example.entity.base;


import com.example.exception.BaseConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * 统一返回结果类
 */
@Api("通用返回对象")
public class BaseResult<T> implements Serializable {

	@ApiModelProperty(value = "返回值", name = "data")
	private T data;

	@ApiModelProperty(value = "返回码", dataType = "String", name = "message")
	private String message;

	@ApiModelProperty(value = "状态", dataType = "Boolean", name = "state")
	private boolean state = true;

	@ApiModelProperty(value = "编码", dataType = "Integer", name = "code")
	private int code = BaseConstant.CODE_SUCCESS;

	public static <T> BaseResult<T> newSuccess() {
		BaseResult<T> res = new BaseResult<>();
		res.setMessage("success");
		return res;
	}


	public static <T> BaseResult<T> newSuccess(T data) {
		return newSuccess(data, "success");
	}


	public static <T> BaseResult<T> newSuccess(String message) {
		BaseResult<T> res = new BaseResult<>();
		res.setMessage(message);
		return res;
	}


	public static <T> BaseResult<T> newSuccess(T data, String message) {
		BaseResult<T> res = new BaseResult<>();
		res.setData(data);
		res.setMessage(message);
		return res;
	}


	public static <T> BaseResult<T> newError(String message) {
		BaseResult<T> res = new BaseResult<>();
		res.setCode(BaseConstant.CODE_SERVER_ERROR);
		res.setState(false);
		res.setMessage(message);
		return res;
	}

	public static <T> BaseResult<T> newAuthError() {
		BaseResult<T> res = new BaseResult<>();
		res.setCode(BaseConstant.CODE_NOT_ALLOWED);
		res.setState(false);
		res.setMessage("URL访问受限");
		return res;
	}

	public boolean getState() {
		return state;
	}


	public void setState(boolean state) {
		this.state = state;
		code = state ? BaseConstant.CODE_SUCCESS : BaseConstant.CODE_SERVER_ERROR;
	}


	public String getMessage() {
		return message;
	}


	public void setMessage(String message) {
		this.message = message;
	}


	public T getData() {
		return data;
	}


	public void setData(T data) {
		this.data = data;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
		state = (BaseConstant.CODE_SUCCESS == code) ? true : false;
	}
}
